//路由鉴权：鉴权（某一路由什么条件下可以访问、什么条件下不可以访问）
import router from './index'

// @ts-ignore
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import pinia from '@/store'
import { useUserStore } from '@/store/modules/userStore'
//进度条加载时小圆球丢弃
NProgress.configure({ showSpinner: false })
let userStore = useUserStore(pinia)
//全局前置路由守卫
router.beforeEach(async (to: any, from: any, next: any) => {
  NProgress.start()
  document.title = to.meta.title
  console.log(to.meta.title)
  if (userStore.token) {
    if (to.path === '/login') {
      next(to.query.redirect)
    } else {
      //验证用户信息是否存在
      if (userStore.userName) {
        next()
      } else {
        try {
          await userStore.userInfo()
          next()
        } catch (error) {
          await userStore.userLogout()
          next({ path: '/login', query: { redirect: to.path } })
        }
      }
    }
  } else {
    // 如果不判断 会陷入死循环
    if (to.path === '/login') {
      next()
    } else {
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
})
//全局后置路由守卫
router.afterEach((to: any, from: any) => {
  NProgress.done()
})
//实现切换路由进度条业务 安装 pnpm install --save nprogress
